<!--
*  2021-03-15
*  纱线出库
-->
<template>
  <div id="app" class="list-operate">
    <!-- 头部导航 -->
    <van-nav-bar
      title="纱线出库"
      ref="header"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
      @click-right="onClickRight"
    >
      <template #right>
        <van-icon name="scan" size="20" />
      </template>
    </van-nav-bar>
    <!-- 总计 -->
    <van-cell
      :title="'标重: ' + weight"
      :label="'沙包数: ' + tableData.length"
      :value="'筒只数: ' + spindleNum"
      class="list-operate__cell"
    ></van-cell>
    <better-scroll
      class="public-scroll"
      :data="tableData"
      :totalPage="totalPage"
    >
      <van-cell-group v-show="tableData.length !== 0">
        <van-swipe-cell v-for="(data, index) in tableData" :key="index">
          <van-cell :title="'编号: ' + data.standardNo">
            <template slot="label">
              <div class="list-operate-cell">
                <span>
                  <span>色号: </span
                  ><van-field readonly :value="data.colorName"
                /></span>
                <span>
                  <span>规格: </span
                  ><van-field readonly :value="data.standardName"
                /></span>
                <span>
                  <span>区域:</span>
                  <van-field
                    readonly
                    clickable
                    name="picker"
                    :value="data.storeArea"
                  />
                </span>
                <span>
                  <span>重量: </span><van-field readonly :value="data.weight"
                /></span>
                <span>
                  <span>筒管颜色: </span
                  ><van-field readonly :value="data.spindleColor"
                /></span>
                <span>
                  <span>沙包批号: </span
                  ><van-field readonly :value="data.lotNum"
                /></span>
              </div>
            </template>
            <template>
              <span v-html="data.id"></span>
            </template>
          </van-cell>
          <template #right>
            <van-button
              square
              type="danger"
              text="删除"
              @click="onDelete(index)"
            />
          </template>
        </van-swipe-cell>
      </van-cell-group>
      <van-empty
        class="custom-image"
        image="https://img01.yzcdn.cn/vant/custom-empty-image.png"
        v-show="tableData.length === 0"
        description="暂无数据"
      />
    </better-scroll>

    <van-cell-group class="list-operate-btn" v-show="tableData.length !== 0">
      <van-button block type="info" class="bgColor" @click="onClickSubmit"
        >确认出库</van-button
      >
    </van-cell-group>
  </div>
</template>

<script>
import { openWin, getFloat } from "@/utils/index";
import {
  getYarnPackageFilter,
  getYarnStoreOutSingle,
  getYarnStoreOutMerge,
  getYarnPlanInfo,
} from "@/api/yarn";

import { setYarnList, getYarnList, removeYarnList } from "@/utils/auth";

export default {
  name: "weavingOutboundListOperate",
  data() {
    return {
      title: "纱线出库",
      currentPage: 1,
      totalPage: 1,
      tableData: [
        // {
        //   standardNo: "xxxx",
        //   colorName: "xxxx",
        //   standardName: "10/1",
        //   storeArea: "3-A",
        //   weight: "50",
        //   spindleColor: "xxxx",
        //   lotNum: "2",
        // },
      ],
      index: 0,
      showPicker: false,
      columns: [],
      storeArea: "",
      spindleNum: 0,
      weight: 0,
      isMerge: false,
      craftId: 0,   //织造出库扫码的盘头ID
    };
  },
  watch: {
    //  监听入库数据
    tableData: {
      handler(nerArr) {
        this.spindleNum = getFloat(this.countTotal(nerArr, "spindleNum"), 0);
        this.weight = getFloat(this.countTotal(nerArr, "weight"), 1);
      },
      deep: true,
    },
  },
  mounted() {
    const that = this;
    if (process.env.NODE_ENV === "production") {
      this.$nextTick(() => {
        that.initFn(that);
      });
    } else {
      window.apiready = function () {
        that.initFn(that);
      };
    }
  },
  methods: {
    //初始化
    initFn(that) {
      removeYarnList();
      that.isMerge = window.api.pageParam.isMerge;
      window.api.addEventListener({
        name:'viewdisappear'
      }, function() {
        window.api.closeWin();
      });
    },
    // 返回上一页
    onClickLeft() {
      removeYarnList();
      if (!this.isMerge) {
        openWin("outbound-list");
      } else {
        openWin("outbound-yarn");
      }
    },
    // 扫码
    onClickRight() {
      this.fnOpenFNScanner();
    },
    // 扫码
    fnOpenFNScanner() {
      const that = this;
      const zyHmsScan = api.require('zyHmsScan');
      zyHmsScan.openDefaultView({}, ret => {
        if(ret.status) {
          let content = ret.result;
          if (that.isMerge) {
            // 合纱
            if (!that.$isJSON(content) || content.indexOf(",") == -1) {
              that.$toast.fail("二位码异常");
              return false;
            }

            let ids = eval(content);
            if (ids.toString().indexOf(",") == -1) {
              that.$toast.fail("二位码异常");
              return false;
            }
            let id = ids.split(",")[0];
            getYarnPackageFilter(id, (res) => {
              if (that.tableData.length === 0) {
                that.tableData.push(res);
                that.$toast({
                  type: "loading",
                  message: "请等待",
                  duration: 1000,
                  onClose: () => {
                    that.fnOpenFNScanner();
                  },
                });
              } else {
                let result = false;
                that.tableData.forEach((item) => {
                  if (item.id == id) {
                    result = true;
                  }
                });
                if (result) {
                  that.$toast.fail("请勿重复扫码");
                } else {
                  that.tableData.push(res);
                  that.$toast({
                    type: "loading",
                    message: "请等待",
                    duration: 1000,
                    onClose: () => {
                      that.fnOpenFNScanner();
                    },
                  });
                }
              }
            });
          } else {
            let index = content.indexOf("taskId=");
            if (index != -1) {
              let taskId = content.slice(index + 7, content.length);
              getYarnPlanInfo(
                  {
                    taskId: taskId,
                  },
                  (res) => {
                    let yarnList = [];
                    if (getYarnList()) {
                      yarnList = getYarnList();
                    }
                    if (res && res.length) {
                      res.forEach((item) => {
                        yarnList.push(item.yarnId);
                      });

                      let list = [...new Set(yarnList)];
                      setYarnList(list);

                      //设置盘头ID
                      that.craftId = res[0].craftId;

                      that.$toast({
                        type: "success",
                        message: "扫码成功，继续出库",
                        duration: 1000,
                        onClose: () => {
                          that.fnOpenFNScanner();
                        },
                      });
                    }
                  }
              );
            } else {
              if (!that.$isJSON(content) || content.indexOf(",") == -1) {
                that.$toast.fail("二位码异常");
                return false;
              }

              let ids = eval(content);
              if (ids.toString().indexOf(",") == -1) {
                that.$toast.fail("二位码异常");
                return false;
              }
              let id = ids.split(",")[0];
              getYarnPackageFilter(id, (res) => {
                let yarnList = getYarnList() || [];
                if (yarnList.length === 0) {
                  that.$toast.fail("请先扫生产码");
                  return false;
                } else {
                  let index = yarnList.findIndex(
                      (item) => item === res.standardId
                  );
                  if (index === -1) {
                    that.$toast.fail("非所需纱线,请扫相应生产码");
                    return false;
                  } else {
                    if (that.tableData.length === 0) {
                      that.tableData.push(res);
                      that.$toast({
                        type: "loading",
                        message: "请等待",
                        duration: 1000,
                        onClose: () => {
                          that.fnOpenFNScanner();
                        },
                      });
                    } else {
                      let result = false;
                      that.tableData.forEach((item) => {
                        if (item.id == id) {
                          result = true;
                        }
                      });
                      if (result) {
                        that.$toast.fail("请勿重复扫码");
                      } else {
                        that.tableData.push(res);
                        that.$toast({
                          type: "loading",
                          message: "请等待",
                          duration: 1000,
                          onClose: () => {
                            that.fnOpenFNScanner();
                          },
                        });
                      }
                    }
                  }
                }
              });
            }
          }
        }
      });

    },
    // 删除
    onDelete(index) {
      this.tableData.splice(index, 1);
    },
    // 提交
    onClickSubmit() {
      let datas = [];
      let that = this;
      this.tableData.forEach((item) => {
        // let params = {};
        // params.packageId = item.id;
        // params.refType = item.refType;
        // params.storeArea = item.storeArea;
        datas.push(item.id);
      });
      if (!this.isMerge) {
        getYarnStoreOutSingle(
          {
            packageIds: datas,
            refId: that.craftId
          },
          () => {
            this.$toast({
              type: "success",
              message: "出库成功",
              onClose: () => {
                this.storeArea = "";
                openWin("outbound-list");
              },
            });
          },
          (ret) => {
            console.log(ret);
            // alert(JSON.stringify(ret))
          }
        );
      } else {
        getYarnStoreOutMerge(
          {
            packageIds: datas,
          },
          () => {
            this.$toast({
              type: "success",
              message: "出库成功",
              onClose: () => {
                this.storeArea = "";
                openWin("outbound-yarn");
              },
            });
          }
        );
      }
    },
    // 计算总重量
    countTotal(arr, keyName) {
      let $total = 0;
      $total = arr.reduce(function (total, currentValue) {
        return currentValue[keyName] ? total + currentValue[keyName] : total;
      }, 0);
      return $total.toFixed(2);
    },
  },
};
</script>

<style lang="scss">
.list-operate {
  // padding-top: 22px;
  .van-nav-bar__title {
    .van-button {
      height: 36px;
      line-height: 36px;
    }
  }
  .list-operate__cell {
    .van-cell__title {
      flex: 0 0 67% !important;
      display: flex;
      justify-content: space-between;
      span,
      .van-cell__label {
        display: flex;
        flex: 1;
      }
      .van-cell__label {
        justify-content: center;
      }
    }
    .van-cell__value {
      flex: 0 0 33%;
    }
    span,
    .van-cell__label {
      font-weight: 900;
      color: #96b327;
      font-size: 14px;
    }
  }
  .public-scroll {
    height: calc(100vh - 194px);
    overflow: hidden;
    .van-cell {
      .van-cell__title {
        flex: 0 0 100% !important;
      }
    }
    .list-operate-cell {
      display: flex;
      flex-wrap: wrap;
      padding-top: 0;
      & > span {
        display: flex;
        width: 50%;
        height: 30px;
        align-items: center;
        & > span {
          width: 100px;
        }
        .van-cell.van-field {
          padding-left: 0;
        }
      }
    }
  }
  .list-operate-btn {
    padding: 16px;
    &.van-hairline--top-bottom::after,
    .van-hairline-unset--top-bottom::after {
      border-width: 0;
    }
  }
  .van-swipe-cell__right {
    .van-button {
      height: 100%;
    }
  }
}
</style>
